
<!--
 * @Author: Wangtao
 * @Date: 2020-10-22 19:27:39
 * @LastEditors: Wangtao
 * @LastEditTime: 2020-12-25 19:05:24
-->
<template>
  <continer>
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="search"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="search">查询</el-button>
      <el-button size="mini" @click="showGroup" v-functions="['display_number_group']">分组</el-button>
    </template>
    <template slot="content">
      <configTable
        :headers="tableHeaders"
        :data="tableData"
        :pagingData="pagingData"
        @pageChange="pageChange"
        @pageSizeChange="pageSizeChange"
        @checkHeadersChange="checkHeadersChange"
        :selection='true'
        :batchs="batchs"
        @batchClick='batchClick'
        ref='explicitTabel'
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              :show-overflow-tooltip="true"
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="index"
              :sortable="item.sortable"
               v-if="!['oprate', 'group', 'status'].includes(item.prop)"
            >
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'oprate'"
              :prop="item.prop"
              :label="item.label"
              :key="index"
              :width="68"
            >
              <template slot-scope="scope">
                <span @click="editExplicit(scope.row)" v-functions="['display_number_edit']" class="oprate-span"
                  >编辑</span
                >
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'group'"
              :prop="item.prop"
              :label="item.label"
              :key="index"
            >
              <template slot-scope="scope">
                {{scope.row.group | fileterGroup}}
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'status'"
              :prop="item.prop"
              :label="item.label"
              :key="index"
            >
              <template slot-scope="{ row }">
                <span v-if="row.status === 'enable'">启用</span>
                <span v-else>停用</span>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <el-drawer
        custom-class="m7-drawer"
        :title="'编辑分组'"
        :visible.sync="isShowDrawer"
        :append-to-body="true"
        direction="rtl"
        ref="drawer"
      >
        <EditGroup
          v-if="isShowDrawer"
          @cancel="isShowDrawer = false"
          @success="saveGroupSuccess"
          :groupList="groupList"
        ></EditGroup>
      </el-drawer>
      <el-drawer
        custom-class="m7-drawer"
        :title="'编辑外显号'"
        :visible.sync="isShowExplicitDrawer"
        :append-to-body="true"
        direction="rtl"
        ref="drawer"
      >
        <EditExplicit
          @cancel="isShowExplicitDrawer = false"
          :groupList="groupList"
          :numberList="numberList"
          :currentGroupList="currentGroupList"
          @change="explicitUpdateSuccess"
          v-if="isShowExplicitDrawer"
        ></EditExplicit>
      </el-drawer>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/configCommon/table.vue'
import { NumberModule } from '@/store/modules/config/number'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import { deepClone } from '@/utils/common'
import EditGroup from './EditGroup.vue'
import EditExplicit from './EditExplicit.vue'
import { GroupObject, SaveGroupParams, ResGroupSave, CreateOrUpdateParams, QueryGroupParams, ExplicitData, Batch } from './types/group'
import { Store } from 'vuex/types/index'
import { ElMessage } from 'element-ui/types/message'
interface PageData {
  total: number
  limit: number
  page: number
}
@Component({
  name: 'ExplicitNumber',
  components: { continer, configTable, QuickSearch, EditGroup, EditExplicit },
  filters: {
    fileterGroup (group: string[]) {
      if (group && group.length > 0) {
        return group.join(',')
      }
    }
  }
})
export default class extends Vue {
  private $message: ElMessage | undefined
  private $store: Store<any> | undefined
  private groupList: GroupObject[] | undefined
  private pagingData: PageData = { total: 0, limit: 10, page: 1 } // 翻页相关的数据控制
  private agents: object[] = [{}] // 外显号应用座席
  private typeArr: object[] = [ // 外显号类型
    { name: '小号', _id: 'xNumber' },
    { name: '固话号码', _id: 'trunkNumber' }
  ]

  private statusArr: object[] = [ // 外显号类型
    { name: '停用', _id: 'disable' },
    { name: '启用', _id: 'enable' }
  ]

  private tableHeaders: object[] = [ // 基本表头配置信息
    { label: '外显号', prop: 'number' },
    { label: '类型', prop: 'typeName' },
    { label: '状态', prop: 'status' },
    { label: '应用座席', prop: 'usersName', sortable: true },
    { label: '创建时间', prop: 'createTime' },
    { label: '分组', prop: 'group' },
    { label: '操作', prop: 'oprate' }
  ]

  private quickSearchForm: any = { // 快捷检索数据（外显号，应用座席，类型）
    form: {},
    advSearchOptions: [] // 快捷检索的数据(语音文件名称)
  }

  private batchs: Batch[] = [{
    name: '批量编辑',
    action: 'batchEdit'
  }]

  private checkHeaders: [] = [] // 当前展示的表头信息

  private tableData: object[] = [] // table中展示的数据

  private isShowDrawer: boolean = false

  private isShowExplicitDrawer: boolean = false

  // 外显号列表
  private numberList: string[] = []
  private currentGroupList: string[] | undefined

  private search () { // 点击查询
    this.pagingData.page = 1
    this.fetchData()
  }

  private pageChange (page) { // 翻页
    this.pagingData.page = page
    this.fetchData()
  }

  private pageSizeChange (size) { // 每页多少条数据
    this.pagingData.limit = size
    this.pagingData.page = 1
    this.fetchData()
  }

  private checkHeadersChange (checkList) { // 设置表头
    this.$set(this, 'checkHeaders', checkList)
  }

  private fetchData () { // 查列表
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page }, this.quickSearchForm.form)
    const data = { url: '/call/action/config/displayNumber/query', method: 'POST', data: actionData }
    NumberModule.NumberCommonAction(data).then((res: any) => {
      if (res && res.success) {
        const list = res.list || []
        list.forEach((item: any) => {
          item.usersName = ''
          item.agents.forEach((item2: any) => {
            const agentObj = (this.$store as Store<any>).state.common.publicCache.userListObj[item2]
            item.usersName += agentObj ? `${agentObj.name}, ` : ''
          })
          item.usersName = item.usersName.slice(0, item.usersName.length - 2)
          this.typeArr.forEach((item3: any) => {
            if (item3._id === item.resourceType) {
              item.typeName = item3.name
            }
          })
        })
        this.tableData = list
        this.pagingData.total = res.count || 0
      }
    })
  }

  private beforeMount () {
    this.initQuickSearchForm()
    this.getGroupList()
    this.fetchData()
  }

  private showGroup (): void {
    this.isShowDrawer = true
  }

  private saveGroupSuccess (groupList: GroupObject[]): void {
    const actionData: SaveGroupParams = { group: groupList }
    const data: CreateOrUpdateParams = { url: '/call/action/config/number/group/createOrUpdate', method: 'POST', data: actionData }
    NumberModule.NumberCommonAction(data).then((res: ResGroupSave) => {
      if (res && res.success) {
        this.groupList = res.data.group || []
        this.initQuickSearchForm()
        this.fetchData();
        (this.$message as ElMessage).success({ message: '标签保存成功！' })
      }
    })
    this.isShowDrawer = false
  }

  private getGroupList (): void {
    const data: QueryGroupParams = { url: '/call/action/config/number/group/query', method: 'POST' }
    NumberModule.NumberCommonAction(data).then((res: ResGroupSave) => {
      if (res && res.success) {
        this.groupList = res.data.group || []
        this.initQuickSearchForm()
      }
    })
  }

  private editExplicit (data: ExplicitData): void {
    this.numberList = [data.number]
    this.currentGroupList = data.group
    this.isShowExplicitDrawer = true
  }

  private explicitUpdateSuccess (): void {
    (this.$refs as any).explicitTabel.clearSelection()
    this.getGroupList()
    this.fetchData()
    this.isShowExplicitDrawer = false
  }

  private initQuickSearchForm (): void {
    const userList = deepClone((this.$store as Store<any>).state.common.publicCache.userList) || []
    userList.unshift({ agentName: '无应用座席', _id: 'noBind' })
    this.agents = userList
    this.quickSearchForm = { // 快捷检索数据（时间条件，类型）
      form: {
        number: '',
        agentIds: [],
        resourceTypes: [],
        group: [],
        status: []
      },
      advSearchOptions: [ // 快捷检索的数据(语音文件名称)
        { label: '外显号', inputType: 'input', placeholder: '请输入外显号', name: 'number', clearable: true },
        { label: '应用座席', inputType: 'select', clearable: true, multiple: true, selectData: userList, name: 'agentIds', defaultProp: { label: 'agentName', value: '_id' } },
        { label: '类型', inputType: 'select', clearable: true, multiple: true, selectData: this.typeArr, name: 'resourceTypes' },
        { label: '分组', inputType: 'select', clearable: true, multiple: true, selectData: this.groupList, name: 'group' },
        { label: '状态', inputType: 'select', clearable: true, multiple: true, selectData: this.statusArr, name: 'status' }
      ]
    }
  }

  private batchClick (action: string, selectList: string[]): void {
    this.numberList = selectList
    this.currentGroupList = []
    this.isShowExplicitDrawer = true
  }
}
</script>

<style lang="stylus" scoped>
.oprate-span, .radio-span
  cursor pointer
  color $c-main
.delete-span
  color $c-danger
  padding-left 10px
.radio-span
  width 24px
  height 24px
  display inline-block
  background #fff
  margin 2px 0px 2px 0
  box-shadow 0px 1px 3px 0px rgba(216, 222, 230, 0.9)
  border-radius 50%
  font-size 12px
  color $c-main
  text-align center
  vertical-align middle
  &:last-child
    margin-right 0
    margin-left 10px
</style>
